<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <script type="text/javascript" src="JsTpl-0.3.js"></script>
</head>
<body>

<div id="cart1">

</div>

<div id="cart2">

</div>

<script type="text/jsTpl" id="cart-items" data-method="cart.items">
    <table>
    {{ var i = 0, len = context.length, style, p; }}
    {{ for(; i < len; i++): }}
        {{ p = context[i]; }}
        <tr>
            {{ style = p.price > 100 ? 'style="color:red"' : '';}}
            <td data-id={{ p.id }} {{ style }}>
                {{ p.name }}
            </td>
            <td>
                {{ p.price }}
            </td>
        </tr>
    {{ endfor; }}
    </table>
</script>

<script type="text/javascript">
    var cartItems = [
        {id: 1, name: 'product1', price: 60},
        {id: 2, name: 'product2', price: 120},
        {id: 3, name: 'product3', price: 80}
    ];

    // 编译以及使用编译后的模板 1)
    var tplStr = document.getElementById('cart-items').innerHTML;
    var tpl = new JsTpl(tplStr).getCTpl();
    var html = tpl.render(cartItems);

    document.getElementById('cart1').innerHTML = html;

    // 为了简化 1) 那几步，在写 template string 的时候，加上 data-method，之后就可以这样，不过要
    // 等到 DOMContentLoaded
    document.addEventListener('DOMContentLoaded', function () {
        html = JsTpl.renderer['cart.items'].render(cartItems);
        document.getElementById('cart2').innerHTML = html;
    });
</script>
</body>
</html>